import { query } from '../../config/db.js';

/**
 * 邮箱配置数据模型
 */
export class EmailConfig {
  constructor(configData) {
    this.id = configData.id;
    this.smtp_host = configData.smtp_host;
    this.smtp_port = configData.smtp_port;
    this.smtp_secure = configData.smtp_secure;
    this.smtp_user = configData.smtp_user;
    this.smtp_pass = configData.smtp_pass;
    this.from_name = configData.from_name;
    this.from_email = configData.from_email;
    this.is_active = configData.is_active;
    this.created_at = configData.created_at;
    this.updated_at = configData.updated_at;
  }

  /**
   * 创建新的邮箱配置
   * @param {Object} configData - 邮箱配置数据
   * @returns {Promise<Object>} 创建的邮箱配置信息
   */
  static async create(configData) {
    const { 
      smtp_host, 
      smtp_port, 
      smtp_secure, 
      smtp_user, 
      smtp_pass, 
      from_name, 
      from_email 
    } = configData;
    
    const sql = `
      INSERT INTO email_config (smtp_host, smtp_port, smtp_secure, smtp_user, smtp_pass, from_name, from_email)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `;
    
    try {
      const result = await query(sql, [
        smtp_host, 
        smtp_port, 
        smtp_secure, 
        smtp_user, 
        smtp_pass, 
        from_name, 
        from_email
      ]);
      
      return await EmailConfig.findById(result.insertId);
    } catch (error) {
      console.error('创建邮箱配置失败:', error);
      throw error;
    }
  }

  /**
   * 根据ID查找邮箱配置
   * @param {number} id - 配置ID
   * @returns {Promise<Object|null>} 邮箱配置信息或null
   */
  static async findById(id) {
    const sql = `
      SELECT * FROM email_config WHERE id = ?
    `;
    
    try {
      const results = await query(sql, [id]);
      return results.length > 0 ? new EmailConfig(results[0]) : null;
    } catch (error) {
      console.error('查找邮箱配置失败:', error);
      throw error;
    }
  }

  /**
   * 获取当前激活的邮箱配置
   * @returns {Promise<Object|null>} 激活的邮箱配置或null
   */
  static async getActiveConfig() {
    const sql = `
      SELECT * FROM email_config WHERE is_active = TRUE ORDER BY updated_at DESC LIMIT 1
    `;
    
    try {
      const results = await query(sql);
      return results.length > 0 ? new EmailConfig(results[0]) : null;
    } catch (error) {
      console.error('获取激活邮箱配置失败:', error);
      throw error;
    }
  }

  /**
   * 获取所有邮箱配置
   * @param {Object} options - 查询选项
   * @returns {Promise<Array>} 邮箱配置列表
   */
  static async findAll(options = {}) {
    const { page = 1, limit = 10 } = options;

    // 确保参数是有效的数字
    const pageNum = parseInt(page) || 1;
    const limitNum = parseInt(limit) || 10;
    const offset = (pageNum - 1) * limitNum;

    console.log('分页参数:', { page, limit, pageNum, limitNum, offset });

    // 先尝试不使用分页的简单查询
    const sql = `SELECT * FROM email_config ORDER BY created_at DESC`;

    try {
      const results = await query(sql);
      console.log('数据库查询原始结果:', results);
      console.log('结果类型:', typeof results);
      console.log('是否为数组:', Array.isArray(results));

      if (!Array.isArray(results)) {
        console.error('查询结果不是数组:', results);
        return [];
      }

      // 手动实现分页
      const startIndex = offset;
      const endIndex = startIndex + limitNum;
      const paginatedResults = results.slice(startIndex, endIndex);

      console.log('分页后的结果:', paginatedResults);

      const mappedResults = paginatedResults.map(config => new EmailConfig(config));
      console.log('映射后的结果:', mappedResults);

      return mappedResults;
    } catch (error) {
      console.error('获取邮箱配置列表失败:', error);
      throw error;
    }
  }

  /**
   * 更新邮箱配置
   * @param {number} id - 配置ID
   * @param {Object} updateData - 要更新的数据
   * @returns {Promise<Object|null>} 更新后的邮箱配置信息
   */
  static async update(id, updateData) {
    const allowedFields = [
      'smtp_host', 'smtp_port', 'smtp_secure', 'smtp_user', 
      'smtp_pass', 'from_name', 'from_email', 'is_active'
    ];
    const updateFields = [];
    const updateValues = [];

    for (const field of allowedFields) {
      if (updateData[field] !== undefined) {
        updateFields.push(`${field} = ?`);
        updateValues.push(updateData[field]);
      }
    }

    if (updateFields.length === 0) {
      throw new Error('没有可更新的字段');
    }

    updateValues.push(id);
    const sql = `
      UPDATE email_config 
      SET ${updateFields.join(', ')}, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;

    try {
      await query(sql, updateValues);
      return await EmailConfig.findById(id);
    } catch (error) {
      console.error('更新邮箱配置失败:', error);
      throw error;
    }
  }

  /**
   * 激活指定的邮箱配置（同时停用其他配置）
   * @param {number} id - 配置ID
   * @returns {Promise<boolean>} 是否激活成功
   */
  static async activate(id) {
    try {
      // 先停用所有配置
      await query('UPDATE email_config SET is_active = FALSE');
      
      // 激活指定配置
      const result = await query('UPDATE email_config SET is_active = TRUE WHERE id = ?', [id]);
      
      return result.affectedRows > 0;
    } catch (error) {
      console.error('激活邮箱配置失败:', error);
      throw error;
    }
  }

  /**
   * 删除邮箱配置
   * @param {number} id - 配置ID
   * @returns {Promise<boolean>} 是否删除成功
   */
  static async delete(id) {
    const sql = 'DELETE FROM email_config WHERE id = ?';
    
    try {
      const result = await query(sql, [id]);
      return result.affectedRows > 0;
    } catch (error) {
      console.error('删除邮箱配置失败:', error);
      throw error;
    }
  }

  /**
   * 测试邮箱配置连接
   * @param {Object} configData - 邮箱配置数据
   * @returns {Promise<boolean>} 连接是否成功
   */
  static async testConnection(configData) {
    try {
      const nodemailer = await import('nodemailer');
      
      const transporter = nodemailer.createTransport({
        host: configData.smtp_host,
        port: configData.smtp_port,
        secure: configData.smtp_secure,
        auth: {
          user: configData.smtp_user,
          pass: configData.smtp_pass
        }
      });

      await transporter.verify();
      return true;
    } catch (error) {
      console.error('邮箱配置连接测试失败:', error);
      return false;
    }
  }

  /**
   * 转换为安全的JSON格式（不包含密码）
   * @returns {Object} 安全的邮箱配置信息
   */
  toSafeJSON() {
    return {
      id: this.id,
      smtp_host: this.smtp_host,
      smtp_port: this.smtp_port,
      smtp_secure: this.smtp_secure,
      smtp_user: this.smtp_user,
      from_name: this.from_name,
      from_email: this.from_email,
      is_active: this.is_active,
      created_at: this.created_at,
      updated_at: this.updated_at
    };
  }
}
